package com.supermap.qdsearch.utils;

import android.content.Context;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by XueQing Wang on 2018/5/17.
 * DP PX sp 转换  设置margin
 */

public class DensityUtils {
    public static int dp2px(Context context, float dpVal)

    {

        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,

                dpVal, context.getResources().getDisplayMetrics());

    }


    /**
     * sp转px
     *
     * @param context
     * @return
     */

    public static int sp2px(Context context, float spVal)

    {

        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,

                spVal, context.getResources().getDisplayMetrics());

    }


    /**
     * px转dp
     *
     * @param context
     * @param pxVal
     * @return
     */

    public static float px2dp(Context context, float pxVal)

    {

        final float scale = context.getResources().getDisplayMetrics().density;

        return (pxVal / scale);

    }


    /**
     * px转sp
     *
     * @param pxVal
     * @return
     */

    public static float px2sp(Context context, float pxVal)

    {

        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);

    }



    /**
     * 设置某个View的margin
     *
     * @param view   需要设置的view
     * @param isDp   需要设置的数值是否为DP
     * @param left   左边距
     * @param right  右边距
     * @param top    上边距
     * @param bottom 下边距
     * @return
     */
    public static ViewGroup.LayoutParams setViewMargin(Context context,View view, boolean isDp, int left, int right, int top, int bottom) {
        if (view == null) {
            return null;
        }

        float leftPx = left;
        float rightPx = right;
        float topPx = top;
        float bottomPx = bottom;
        ViewGroup.LayoutParams params = view.getLayoutParams();
        ViewGroup.MarginLayoutParams marginParams = null;
        //获取view的margin设置参数
        if (params instanceof ViewGroup.MarginLayoutParams) {
            marginParams = (ViewGroup.MarginLayoutParams) params;
        } else {
            //不存在时创建一个新的参数
            marginParams = new ViewGroup.MarginLayoutParams(params);
        }

        //根据DP与PX转换计算值
        if (isDp) {
            leftPx = px2dp(context,left);
            rightPx = px2dp(context,right);
            topPx = px2dp(context,top);
            bottomPx = px2dp(context,bottom);
        }
        //设置margin
        marginParams.setMargins((int) leftPx, (int) topPx, (int) rightPx, (int) bottomPx);
        view.setLayoutParams(marginParams);
        return marginParams;
    }

}
